var comPageNum = 1;//分页公共页码
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
function searchList(pageNum){
    comPageNum = pageNum;
    $.ajax({
        url:  root.couponInter.coupon_querySendCouponAudit,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "sendCouponType":$('#sendCouponType').val(),
            "sendCouponCode":$('#sendCouponCode').val(),
            "sendCouponName":$('#sendCouponName').val(),
            "sendCouponDept":$('#sendCouponDept').val(),
            "sendCouponUser":$('#sendCouponUser').val(),
            "topicCode":$('#topicCode').val(),
            "topicName":$('#topicName').val(),
            "sendCustType":$('#custType').val(),
            "inputStarTime":$('#logmin').val(),
            "inputEndTime":$('#logmax').val(),
            "pageNum": pageNum,
            "pageSize": 10,
        }),
        success: function (data) {
            sessionStorage.setItem("coupon",'')
            console.log(data) ;
            if(data.result.length==0&&comPageNum!=1){
                searchList(comPageNum-1);
                return;
            }
            couponlist(data.result);
            $('.M-box3').pagination({
                pageCount: data.totalPage,
                current:comPageNum,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    comPageNum = api.getCurrent();
                    searchList(api.getCurrent());
                }
            });

            /*$('.M-box3').pagination({
                pageCount: data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url:  root.couponInter.coupon_querySendCouponAudit,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "sendCouponType":$('#sendCouponType').val(),
                            "sendCouponCode":$('#sendCouponCode').val(),
                            "sendCouponName":$('#sendCouponName').val(),
                            "sendCouponDept":$('#sendCouponDept').val(),
                            "sendCouponUser":$('#sendCouponUser').val(),
                            "topicCode":$('#topicCode').val(),
                            "topicName":$('#topicName').val(),
                            "sendCustType":$('#custType').val(),
                            "inputStarTime":$('#logmin').val(),
                            "inputEndTime":$('#logmax').val(),
                            "pageNum": api.getCurrent(),
                            "pageSize":10,
                        }),
                        success: function (result) {
                            console.log(result)
                            couponlist(result.result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });*/
        },
        error: function () {
            $.Huimodalalert('失败！',1000);
        }
    });
}

function couponlist(data) {
    dataSource.splice(0, dataSource.length);//清空数组
    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.sendCouponCode);
        rowData.push(field.sendCouponName);
        rowData.push(field.sendCustType);
        rowData.push(field.sendCouponDept);
        rowData.push(field.sendCouponUser);
        rowData.push(field.sendCouponType);
        rowData.push(field.auditStatus);
        rowData.push(field.createdAt);
        rowData.push(field.sendCouponId);
        rowData.push(field.customerType);
        rowData.push(field.sendCondition);
        rowData.push(field.startTime);
        rowData.push(field.endTime);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "order": [[ 7, "desc" ]],
            "autoWidth": false,
            "ordering": true,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        val = row[1];
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        if(row[5] == 1){
                            if(row[2]==11){
                                val = '签约客户(非分销)';
                            }else if(row[2]==12){
                                val = '签约客户(分销)';
                            }else if(row[2]==20){
                                val = '普通客户';
                            }else{
                                val = '认证客户';
                            }
                        }else{
                            var custArr = row[9].split(",");
                            console.log(custArr);
                            var val = '';
                            for (var i = 0; i < custArr.length; i++) {
                                console.log(custArr[i]);
                                if (custArr[i] == '') {
                                    val += '';
                                }
                                if (custArr[i] == 11) {
                                    val += '签约客户(非分销) </br>';
                                }
                                if (custArr[i] == 12) {
                                    val += '签约客户(分销) </br>';
                                }
                                if (custArr[i] == 20) {
                                    val += '普通客户 </br>';
                                }
                                if (custArr[i] == 30) {
                                    val += '认证客户 </br>';
                                }
                                if (custArr[i] == 40) {
                                    val += '签约客户(非分销)</br> 签约客户(分销)</br> 普通客户</br> 认证客户</br> ';
                                }
                            }
                            console.log(val);
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[5] == 1) {
                            val = '手动发券'
                        }
                        else if (row[5] == 2 && row[10] == 0) {
                            val = '自动发券'
                        }
                        else if (row[5] == 2 && row[10] == 1) {
                            val = '自动发券</br> 新用户注册'
                        }
                        else if (row[5] == 2 && row[10] == 2) {
                            val = '自动发券</br> 满足订单金额条件</br>'
                        } else if (row[5] == 2 && row[10] == 4) {
                            val = '自动发券</br> 按照客户的价格类型</br>'
                        }
                        else if (row[5] == 3) {
                            val = '客户领取发券'
                        }else if (row[5] == 4) {
                            val = '抽奖发送'
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[5]==1){
                            val = '审核成功即时生效';
                        }else{
                            if(row[12]==null || row[12]==''){
                                val = ''+row[11]+'</br> '+'~'+'</br>'+'不限'+'</br>';
                            }else{
                                val = ''+row[11]+'</br> '+'~'+'</br>'+row[12]+'</br>';
                            }
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        val = row[3];
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        val = row[4];
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[6] == 10) {
                            val = '待审核';
                            return val;
                        }
                        return val;
                    },
                    "targets": 7
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        val = row[7];
                        return val;
                    },
                    "targets": 8
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a class="powerButton 154"><span class="list" onclick="check(\'发券审核\',\'coupon-check-2.html\',\'' + row[8] + '\')">审核</span>&nbsp;&nbsp;</a>';
                        return val;
                    },
                    "targets": 9
                }
            ]
        });
        //权限控制函数
        power()
    };
}
function check(title,url,sendCouponId) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url +'?sendCouponId='+sendCouponId
    });
    layer.full(index);
}

var flag1 = true;
$('#sendCouponDept').on('compositionstart',function(){
    flag1 = false;
})
$('#sendCouponDept').on('compositionend',function(){
    flag1 = true;
})
$('#sendCouponDept').on('input',function(){
    var _this = this;
    setTimeout(function(){
        if(flag1){
            var value=$(_this).val();
            $('li').remove();
            $.ajax({
                url: root.accessInter.access_department_listDepartment,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                data:{
                    "keywords":value
                },
                success: function (data) {
                    console.log(data);
                    if(value!='')
                    {
                        $(".deptlist").removeClass('hide');
                        for (var i in data.bianmaList) {
                            $("#deptList").append('<li id="'+data.bianmaList[i].BIANMA+'" class="depts">' + data.bianmaList[i].DEPARTMENT_NAME + '</li>');
                        }
                    }
                    else{
                        document.getElementsByClassName('deptlist')[0].classList.add('hide');
                    }
                    $('.depts').on('click',function () {
                        $('#sendCouponDept').val(this.innerHTML);
                    })
                }
            });
        }
    },0)
})

var flag2 = true;
$('#sendCouponUser').on('compositionstart',function(){
    flag2 = false;
})
$('#sendCouponUser').on('compositionend',function(){
    flag2 = true;
})
$('#sendCouponUser').on('input',function(){
    var _this = this;
    setTimeout(function(){
        if(flag2){
            var value=$(_this).val();
            $('li').remove();
            $.ajax({
                url: root.accessInter.access_listUsername,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                data:{
                    "keywords":value
                },
                success: function (data) {
                    console.log(data.userName);
                    if(value!='')
                    {
                        $(".userlist").removeClass('hide');
                        for (var i in data.userName) {
                            $("#userList").append('<li id="'+data.userName[i].USER_ID+'" class="users">'+data.userName[i].NAME+'</li>');
                        }
                    }
                    else{
                        document.getElementsByClassName('userlist')[0].classList.add('hide');
                    }
                    $('.users').on('click',function () {
                        $('#sendCouponUser').val(this.innerHTML);
                    })
                }
            });
        }
    },0)
})

$(document).click(function(e) {
    var target = $(e.target);
    if(target[0].id!='sendCouponDept'){
        $('.depts').remove();
        $('.deptlist').addClass('hide');
    }
    if(target[0].id!='sendCouponUser'){
        $('.users').remove();
        $('.userlist').addClass('hide');
    }
})

//弹框跳转
var coupon= sessionStorage.getItem("coupon")
if(coupon==10){
    searchList(1)
}
